# -*- coding: utf-8 -*-
import random
import sys

import pygame.mixer
from pygame.locals import *
from setting import *
from utils import *
from xiaoqiu.Ball import Ball



# 循环 开始游戏
from xiaoqiu.player import Mouse


def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:  # Pressing ESC quits.
                    terminate()
                elif event.key == K_1:
                    return 1
                elif event.key == K_2:
                    return 2
                elif event.key == K_3:
                    return 3

# 终止和暂停游戏
def terminate():
    pygame.quit()
    sys.exit()

# 文本渲染函数
def drawText(text, font, surface, x, y, textcolor):
    textobj = font.render(text, 1, textcolor)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

# 初始化画布
screen, background = makeGameBg(WIDTH, HEIGHT)
# 设置字体声音图片
font = pygame.font.Font('../fengheguai.otf', 40)  # 48 字体大小
dead_sound = pygame.mixer.Sound('../sounds/dead.mp3')


def main():

    # 开始游戏
    screen.fill(BG_COLOR)
    drawText('躲避红球', font, screen, (WIDTH / 9), (HEIGHT / 3), (0,0,0))
    drawText('按1、2、3选择不同难度', font, screen, (WIDTH / 9), (HEIGHT / 3) + 50, (0,0,0))
    pygame.display.update()
    clock = pygame.time.Clock()

    # 游戏开始页面
    ladderNum = waitForPlayerToPressKey()



    comeAgain = ballCome()
    # --------------------------------------------------
    # --------------------对象存储-------------------------
    global TIME, SCORE
    balls = pygame.sprite.Group(Ball(judgeDiff(ladderNum, TIME)))
    mouse = Mouse(howBigBallIs(ladderNum, TIME))
    mouseObject = pygame.sprite.Group(mouse)

    record_score = 1

    # --------------------------------------------------
    # 读取最高分
    with open('record.txt','r') as f:
        record = f.readline()
        record_score = int(record)
        print(record_score)
    f.close()

    # ---------------------游戏主程序-----------------------
    RUNNING = True
    SHOWINFO = False
    while True:
        draw(screen, SCORE, TIME)  # 动态添加文字
        if SHOWINFO:
            if SCORE > record_score:
                with open('record.txt','w') as f:
                    f.write(str(int(SCORE)))
                f.close()
            makeTips('Please Press The Space To Restart', 30, (0,0,0), (WIDTH / 2 - 240, HEIGHT / 2 - 50),
                     screen)
            makeTips('您的分数为：'+str(SCORE), 30, (34, 139, 34), (WIDTH / 2 - 240, HEIGHT / 2 - 110),
                     screen)
            makeTips('最高分为：'+str(record_score), 30, (255, 99, 71), (WIDTH / 2 - 240, HEIGHT / 2 - 80),
                     screen)



        for each in balls:
            if pygame.sprite.spritecollide(each, mouseObject, False, collided=None) and each.timeSec > 2:

                RUNNING = False
                SHOWINFO = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)
            elif event.type == pygame.KEYDOWN:  # 重新开始
                if event.key == pygame.K_SPACE:
                    SCORE = 0
                    TIME = 0
                    for each in balls.sprites():
                        balls.remove(each)
                    SHOWINFO = False
                    RUNNING = True
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

            elif event.type == comeAgain and RUNNING:  # 每秒增加
                TIME += 1
                ballsNum = ballNum(ladderNum, TIME)
                diff = judgeDiff(ladderNum, TIME)
                SCORE += (ballsNum * diff[3])
                if TIME in [10, 20]:
                    mouseObject.remove(mouseObject.sprites()[0])
                    mouseObject.add(Mouse(howBigBallIs(ladderNum, TIME)))
                if len(balls) < ballsNum:
                    balls.add(Ball(diff))
                for each in balls:  # 防止误触的保护罩
                    each.timerAdd()
        balls.update(screen, protectTime(ballNum(ladderNum, TIME)))

        mouseObject.update(screen)
        clock.tick(FPS)
        pygame.display.update()  # 刷新
    print('游戏结束')

if __name__ == '__main__':
    main()